﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BOMS.DAL;
using System.Data;
using System.IO;
using BOMS.Utility;

namespace BOMS.WebUI.Web.Warning
{
    public partial class warningStat : System.Web.UI.Page
    {
        public DateTime dtmBegin
        {
            get
            {
                if (txtDtmBegin.Text.Trim() == "")
                {
                    return new DateTime(2012, 1, 1);
                }
                else
                {
                    return DateTime.Parse(txtDtmBegin.Text.Trim());
                }
            }
        }
        public DateTime dtmEnd
        {
            get
            {
                if (txtDtmEnd.Text.Trim() == "")
                {
                    return new DateTime(2050, 1, 1);
                }
                else
                {
                    return DateTime.Parse(txtDtmEnd.Text.Trim());
                }
            }
        }
        private BLL.S_BatSnapshot bll = new BLL.S_BatSnapshot();
        protected void Page_Load(object sender, EventArgs e)
        {
            drpEquip.SelectedIndexChanged += new EventHandler(drp_SelectedIndexChanged);
            drpBatgrp.SelectedIndexChanged += new EventHandler(drp_SelectedIndexChanged);
            if (!IsPostBack)
            {
                
                //设置排序
                this.GridView_history.Attributes.Add("SortExpression", "warningtime");
                this.GridView_history.Attributes.Add("SortDirection", "ASC");

                ViewState["SortOrder"] = "warningtime";
                ViewState["OrderDire"] = " ASC"; 
                BindDropdownlist(drpEquip);
            }
        }  
        void BindDropdownlist(object aim)
        {
             DropDownList drp = (DropDownList)aim;
             
            List<string> li = null;
            Dictionary<string, string> dict = null;
            if (drp == drpEquip)
            {
              // li = bll.GetEquipList();
               dict = bll.GetEquipList();

               foreach (KeyValuePair<string, string> kvp in dict)
               {
                   ListItem Item = new ListItem(kvp.Value, kvp.Key);
                   if (!drp.Items.Contains(Item))
                   {
                       drp.Items.Add(Item);
                   }
               }

            }else if(drp == drpBatgrp)
            {
                 li = bll.GetBatgrpList(drpEquip.SelectedValue);
                 //li.Add("0");//通信中断时，查不到电池组信息

                 drp.Items.Clear();
                 ListItem defaultItem = new ListItem("所有电池组", "");
                 drp.Items.Add(defaultItem);

                 for (int i = 0; i < li.Count; i++)
                 {
                     ListItem it = new ListItem(li[i], li[i]);
                     if (!drp.Items.Contains(it))
                     {
                         drp.Items.Add(it);
  
                     }
                 }   
            }
            else if(drp == drpBattery)
            {
                li = bll.GetBatteryList(drpEquip.SelectedValue,drpBatgrp.SelectedValue);

                drp.Items.Clear();
                ListItem defaultItem = new ListItem("所有电池", "");
                drp.Items.Add(defaultItem);

                for (int i = 0; i < li.Count; i++)
                {
                    ListItem it = new ListItem(li[i], li[i]);
                    if (!drp.Items.Contains(it))
                    {
                        drp.Items.Add(it);
                    }
                }   
            }
        }
        protected void btn_submit_Click(object sender, EventArgs e)
        {
            int rowcount;
            bindData(out rowcount);
            if (rowcount > 0)
            {
                Button2.Enabled = true;
            }
            
        }
        protected void btnChart_Click(object sender, EventArgs e)
        {
            string url = "WarningStatusChart.aspx?equipid={0}&batgrp={1}&batid={2}&dtmbegin={3}&dtmend={4}&hostName={5}";
            url = string.Format(url, drpEquip.SelectedValue, drpBatgrp.SelectedValue, drpBattery.SelectedValue, dtmBegin.ToString("yyyy-MM-dd hh:mm:ss"), dtmEnd.ToString("yyyy-MM-dd hh:mm:ss"), drpEquip.SelectedItem.Text);
            Response.Redirect(url);
        }
        private void bindData(out int RowCount)
        {
            string equipid=this.drpEquip.SelectedValue;
            string batterygroup=this.drpBatgrp.SelectedValue;
            string batteryId = this.drpBattery.SelectedValue;
            string beginWarningtime = dtmBegin.ToString("yyyy-MM-dd HH:mm:ss");
            string endWarningtime = dtmEnd.ToString("yyyy-MM-dd HH:mm:ss");
            string warningstatus=this.drp_warningStatus.SelectedValue;
            // 获取GridView排序数据列及排序方向
            string sortExpression = this.GridView_history.Attributes["SortExpression"];
            string sortDirection = this.GridView_history.Attributes["SortDirection"];
            // 调用业务数据获取方法
            DataSet ds = WarningHistory.getWarningHistory(equipid, batterygroup, batteryId, beginWarningtime, endWarningtime, warningstatus);
            DataTable dt = ds.Tables[0];

            // 根据GridView排序数据列及排序方向设置显示的默认数据视图
            if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
            {
                dt.DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
            }

            
            this.GridView_history.DataSource = dt;
            this.GridView_history.DataBind();

            //this.Label_begin.Text = this.txtDtmBegin.Text == "" ? dtmBegin.ToString() : txtDtmBegin.Text;
            //this.Label_end.Text = this.txtDtmEnd.Text == "" ? dtmEnd.ToString() : txtDtmEnd.Text;
            this.Label_begin.Text = this.txtDtmBegin.Text == "" ? "上线" : this.txtDtmBegin.Text;
            this.Label_end.Text = this.txtDtmEnd.Text == "" ? "今天" : this.txtDtmEnd.Text;
            this.Label_count.Text = ds.Tables[0].Rows.Count.ToString();
            this.Label_wince.Text = this.drpEquip.SelectedItem.Text;
            this.Label_group.Text = this.drpBatgrp.SelectedItem.Text;
            Label_battery.Text = this.drpBattery.SelectedItem.Text;
            RowCount = ds.Tables[0].Rows.Count;
        }
        void drp_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList drp = (DropDownList)sender;
            if (drp == drpEquip)
            {
                BindDropdownlist(drpBatgrp);
            }
            else if (drp == drpBatgrp)
            {
                BindDropdownlist(drpBattery);
            }
        }

        protected void GridView_history_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //排序图标
            if (e.Row.RowType == DataControlRowType.Header)
            {
                ShowSortedIcon(GridView_history, e.Row);
            }
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //当鼠标停留时更改背景色
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#abcdef'");
                //当鼠标移开时还原背景色
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                if (e.Row.Cells[2].Text == "-1")
                {
                    e.Row.Cells[2].Text = "[整组]";
                }

                DataRowView dr = e.Row.DataItem as DataRowView;
                string ImgTextStr = "";
                if (dr != null)
                {
                    if ((int)dr["BatteryID"] == -1)
                    {
                        ImgTextStr = Common.BuildWarningString<GroupErrorStatus>((int)dr["WarningNO"],true);
                    }
                    else
                    {
                        ImgTextStr = Common.BuildWarningString<BatteryErrorStatus>((int)dr["WarningNO"], true);
                    }
                }
                e.Row.Cells[3].Text = ImgTextStr;
            }
            
        }

        protected void GridView_history_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "select")
            {
            int rowIndex = Convert.ToInt32(e.CommandArgument);
            if (rowIndex > -1)
            {
                string id = this.GridView_history.DataKeys[rowIndex].Value.ToString();
              
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "info", "<script language=\"javascript\">zOpen('select'," + id + ");</script>"); 
                }
            }
        }
        protected void ShowSortedIcon(GridView gvData, GridViewRow gvRow)
        {
            for (int index = 0; index <= gvData.Columns.Count - 1; index++)
            {
                if ((gvData.Columns[index].SortExpression == gvSortExpression) && (gvData.Columns[index].SortExpression != ""))
                {
                    Image img = new Image();
                    if ((string)ViewState["OrderDire"] == " ASC")
                    {
                        img.ImageUrl = "../../Images/asc.png";
                        img.ToolTip = "递增排列";
                    }
                    else
                    {
                        img.ImageUrl = "../../Images/desc.png";
                        img.ToolTip = "递减排列";
                    }
                    gvRow.Cells[index].Controls.Add(img);
                }
            }
        }
        private string gvSortExpression
        {
            get
            {
                if (ViewState["SortOrder"] != null && ViewState["SortOrder"].ToString() != string.Empty)
                { return ViewState["SortOrder"].ToString(); }
                else
                { return ""; }
            }
            set
            { ViewState["SortOrder"] = value; }
        }   
        protected void btnExcel_Click(object sender, EventArgs e)
        {
            GridView_history.BorderWidth = 0;
            Response.Clear();
            Response.BufferOutput = true;
            //设定输出的字符集
            Response.Charset = "UTF-8";
            //假定导出的文件名为FileName.xls
            //Response.AppendHeader("Content-Disposition", "attachment;filename=WarningHistory.xls");
            //Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(DateTime.Now.ToString("yyyy-MM-dd") + "报警历史数据.xls", System.Text.Encoding.UTF8) + "\"");
            //设置导出文件的格式
            Response.ContentType = "application/ms-excel";
            string orderDire=ViewState["OrderDire"].ToString();
            string sortOrder=ViewState["SortOrder"].ToString();
            //关闭ViewState
            Page.EnableViewState = false;
            System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("zh-CN", true);
            System.IO.StringWriter stringWriter = new System.IO.StringWriter(cultureInfo);
            System.Web.UI.HtmlTextWriter textWriter = new System.Web.UI.HtmlTextWriter(stringWriter);
            this.GridView_history.RenderControl(textWriter);
            //把HTML写回浏览器
            string css = @"<style>td {border:1px solid #ccc;text-align:center;}</style>";
            Response.Write(css);
            Response.Write(stringWriter.ToString());
            Response.End();
            Page.EnableViewState = true;
            ViewState["OrderDire"] = orderDire;
            ViewState["SortOrder"] = sortOrder;
        }

        public override void VerifyRenderingInServerForm(Control control)
        {

        }

        protected void GridView_history_Sorting(object sender, GridViewSortEventArgs e)
        {
            // 从事件参数获取排序数据列
            string sortExpression = e.SortExpression.ToString();
            // 假定为排序方向为“顺序”
            string sortDirection = "ASC";

            // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
            if (sortExpression == this.GridView_history.Attributes["SortExpression"])
            {
                //获得下一次的排序状态
                sortDirection = (this.GridView_history.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");

                if (ViewState["OrderDire"].ToString() == " Desc")
                {
                    ViewState["OrderDire"] = " ASC";
                    ViewState["SortOrder"] = sortExpression;

                }
                else
                {
                    ViewState["OrderDire"] = " Desc";
                    ViewState["SortOrder"] = sortExpression;
                }
            }

            // 重新设定GridView排序数据列及排序方向
            this.GridView_history.Attributes["SortExpression"] = sortExpression;
            this.GridView_history.Attributes["SortDirection"] = sortDirection;
            gvSortExpression = e.SortExpression;
            int rowcount;
            bindData(out rowcount);
            if (rowcount > 0)
            {
                Button2.Enabled = true;
            }
        }

    }
}